package com.dz.risk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dz.risk.annocation.SystemLog;
import com.dz.risk.common.*;
import com.dz.risk.common.exception.RRException;
import com.dz.risk.dao.RiskFactorDao;
import com.dz.risk.dao.RiskFactorValueDao;
import com.dz.risk.pojo.QueryParams;
import com.dz.risk.pojo.domain.RiskFactorEntity;
import com.dz.risk.pojo.domain.RiskFactorValueEntity;
import com.dz.risk.pojo.domain.TemporaryTableOfDataEntity;
import com.dz.risk.service.RiskFactorService;
import com.dz.risk.service.RiskFactorValueService;
import com.dz.risk.service.TemporaryTableOfDataService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author baohan
 * @className RiskFactorController
 * @date 2021/6/18 16:06
 */
@RestController
@RequestMapping("dz-ftsp/stest/riskFactor")
@Api(tags = "风险因子api", value = "风险因子api接口")
@Slf4j
public class RiskFactorController {

    @Autowired
    RiskFactorService riskFactorService;

    @Autowired
    RiskFactorValueService riskFactorValueService;

    @Autowired
    RiskFactorValueService factorValueService;

    @Autowired
    RiskFactorValueDao riskFactorValueDao;

    @Autowired
    RiskFactorDao riskFactorDao;

    @Autowired
    TemporaryTableOfDataService temporaryTableOfDataService;

    @ApiOperation("导入风险因子表")
    @PostMapping(value = "/readExcel")
    public ResponseVO readExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        //判断文件是否为空
        String name = file.getOriginalFilename();
        Workbook wb = null;
        long size = file.getSize();
        if (null == file || null == name || SysConstant.ZERO == size) {
            return new ResponseVO(-1, "file is null");
        }
        try {
            InputStream inp = file.getInputStream();
            wb = WorkbookFactory.create(inp);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RRException("readExcel IO is error", e.getCause());
        }
        try {
            return riskFactorService.readExcelRiskFactor(wb);
        } catch (RRException e) {
            e.printStackTrace();
            return new ResponseVO(e.getCode(), e.getMessage() + e.getCause().getMessage());
        }
    }

    /**
     * 新增风险内容
     *
     * @param factorEntity
     */
    @ApiOperation("新增风险内容")
    @PostMapping(value = "/add")
    public ResponseVO add(@RequestBody RiskFactorEntity factorEntity) {
        Assert.notNull(factorEntity.getRiskContent(), "riskContent is null error");
        // 重复性校验
        LambdaQueryWrapper<RiskFactorEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RiskFactorEntity::getRiskContent, factorEntity.getRiskContent());
        RiskFactorEntity riskFactorEntity = riskFactorDao.selectOne(queryWrapper);
        if (riskFactorEntity != null) {
            return ResponseVO.fail("Risk factors already exist");
        }
        try {
            riskFactorService.add(factorEntity);
        } catch (RRException e) {
            e.printStackTrace();
            return new ResponseVO(e.getCode(), e.getMessage() + e.getCause().getMessage());
        }
        return new ResponseVO(com.dz.risk.common.enums.CodeEnum.SUCCESS);
    }

    /**
     * 查询风险因子
     *
     * @param queryParams
     */
    @ApiOperation("查询风险因子")
    @PostMapping(value = "/query")
    public ResponseVO queryRiskContent(@RequestBody QueryParams queryParams) {
        List<RiskFactorEntity> riskFactorValueEntities = null;
        try {
            PageHelper.startPage(queryParams.getPageNum(), queryParams.getPageSize());
            riskFactorValueEntities = riskFactorDao.selectRiskFactor();
        } catch (RRException e) {
            e.printStackTrace();
            return new ResponseVO(e.getCode(), e.getMessage() + e.getCause().getMessage());
        }
        return new ResponseVO(new PageInfo<>(riskFactorValueEntities));

    }

    /**
     * 修改风险类容
     *
     * @param factorEntity
     */
    @ApiOperation("修改风险类容")
    @PostMapping(value = "/updateRiskContent")
    public ResponseVO updateRiskContent(@RequestBody RiskFactorEntity factorEntity) {
        Assert.notNull(factorEntity.getId(), "id is null error");
        if (StringUtils.isNotBlank(factorEntity.getRiskContent())) {
            // 重复性校验
            LambdaQueryWrapper<RiskFactorEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RiskFactorEntity::getRiskContent, factorEntity.getRiskContent());
            queryWrapper.ne(RiskFactorEntity::getId, factorEntity.getId());
            RiskFactorEntity riskFactorEntity = riskFactorDao.selectOne(queryWrapper);
            if (riskFactorEntity != null) {
                return ResponseVO.fail("Risk factors already exist");
            }
        }
        try {
            riskFactorService.updateRiskContent(factorEntity);
        } catch (RRException e) {
            e.printStackTrace();
            return new ResponseVO(e.getCode(), e.getMessage() + e.getCause().getMessage());
        }
        return new ResponseVO(com.dz.risk.common.enums.CodeEnum.SUCCESS);
    }

    /**
     * 根据code删除
     *
     * @param factorEntity
     */
    @ApiOperation("根据code删除")
    @PostMapping(value = "/delete")
    public ResponseVO delete(@RequestBody RiskFactorEntity factorEntity) {
        Assert.notNull(factorEntity.getId(), "id is null error");
        try {
            riskFactorService.deleteById(factorEntity.getId());
        } catch (RRException e) {
            e.printStackTrace();
            return new ResponseVO(e.getCode(), e.getMessage() + e.getCause().getMessage());
        }
        return new ResponseVO(com.dz.risk.common.enums.CodeEnum.SUCCESS);
    }

    /**
     * 风险因子数据值查询
     *
     * @param queryParams
     */
    @ApiOperation("风险因子数据值查询")
    @PostMapping(value = "/queryFactorAndValue")
    @SystemLog(operateName = "风险因子数据值查询", actionType = "1")
    public ResponseVO queryFactorAndValue(@RequestBody QueryParams queryParams) {
        PageInfo<RiskFactorValueEntity> pageInfo = null;
        try {
            pageInfo = factorValueService.queryFactorAndValue(queryParams);
        } catch (RRException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return new ResponseVO(e.getMessage());
        }
        return new ResponseVO(pageInfo);
    }

    /**
     * 风险因子数据值修改
     *
     * @param queryParams
     */
    @ApiOperation("风险因子数据值修改")
    @PostMapping(value = "/updateFactorValue")
    public ResponseVO updateFactorValue(@RequestBody RiskFactorValueEntity queryParams) {
        try {
            factorValueService.updateById(queryParams);
            // 同步修改中间表数据
            LambdaQueryWrapper<RiskFactorEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RiskFactorEntity::getRiskCode, queryParams.getRiskCode());
            RiskFactorEntity riskFactorEntity = riskFactorDao.selectOne(queryWrapper);
            Long versionDate = Long.parseLong(queryParams.getVersion().replace("-", ""));
            List<TemporaryTableOfDataEntity> temporaryTableOfDataEntities = new ArrayList<>();
            if(riskFactorEntity != null){
                // 未来一个月轻度
                TemporaryTableOfDataEntity oneMonthMild = new TemporaryTableOfDataEntity();
                oneMonthMild.setIndexId(riskFactorEntity.getInTheNextOneMonthsMildCode());
                oneMonthMild.setIndexValue(queryParams.getInTheNextOneMonthsMild());
                oneMonthMild.setDate(versionDate);
                temporaryTableOfDataEntities.add(oneMonthMild);
                // 未来一个月中度
                TemporaryTableOfDataEntity oneMonthModerate = new TemporaryTableOfDataEntity();
                oneMonthModerate.setIndexId(riskFactorEntity.getInTheNextOneMonthsModerateCode());
                oneMonthModerate.setIndexValue(queryParams.getInTheNextOneMonthsModerate());
                oneMonthModerate.setDate(versionDate);
                temporaryTableOfDataEntities.add(oneMonthModerate);

                // 未来一个月重度
                TemporaryTableOfDataEntity oneMonthSevere = new TemporaryTableOfDataEntity();
                oneMonthSevere.setIndexId(riskFactorEntity.getInTheNextOneMonthsSevereCode());
                oneMonthSevere.setIndexValue(queryParams.getInTheNextOneMonthsSevere());
                oneMonthSevere.setDate(versionDate);
                temporaryTableOfDataEntities.add(oneMonthSevere);

                // 未来两个月轻度
                TemporaryTableOfDataEntity twoMonthMild = new TemporaryTableOfDataEntity();
                twoMonthMild.setIndexId(riskFactorEntity.getInTheNextTwoMonthsMildCode());
                twoMonthMild.setIndexValue(queryParams.getInTheNextTwoMonthsMild());
                twoMonthMild.setDate(versionDate);
                temporaryTableOfDataEntities.add(twoMonthMild);

                // 未来两个月中度
                TemporaryTableOfDataEntity twoMonthModerate = new TemporaryTableOfDataEntity();
                twoMonthModerate.setIndexId(riskFactorEntity.getInTheNextTwoMonthsModerateCode());
                twoMonthModerate.setIndexValue(queryParams.getInTheNextTwoMonthsModerate());
                twoMonthModerate.setDate(versionDate);
                temporaryTableOfDataEntities.add(twoMonthModerate);

                // 未来两个月重度
                TemporaryTableOfDataEntity twoMonthSevere = new TemporaryTableOfDataEntity();
                twoMonthSevere.setIndexId(riskFactorEntity.getInTheNextTwoMonthsSevereCode());
                twoMonthSevere.setIndexValue(queryParams.getInTheNextTwoMonthsSevere());
                twoMonthSevere.setDate(versionDate);
                temporaryTableOfDataEntities.add(twoMonthSevere);

                // 未来三个月轻度
                TemporaryTableOfDataEntity threeMonthsMild = new TemporaryTableOfDataEntity();
                threeMonthsMild.setIndexId(riskFactorEntity.getInTheNextThreeMonthsMildCode());
                threeMonthsMild.setIndexValue(queryParams.getInTheNextThreeMonthsMild());
                threeMonthsMild.setDate(versionDate);
                temporaryTableOfDataEntities.add(threeMonthsMild);

                // 未来三个月中度
                TemporaryTableOfDataEntity threeMonthsModerate = new TemporaryTableOfDataEntity();
                threeMonthsModerate.setIndexId(riskFactorEntity.getInTheNextThreeMonthsModerateCode());
                threeMonthsModerate.setIndexValue(queryParams.getInTheNextThreeMonthsModerate());
                threeMonthsModerate.setDate(versionDate);
                temporaryTableOfDataEntities.add(threeMonthsModerate);

                // 未来三个月重度
                TemporaryTableOfDataEntity threeMonthsSevere = new TemporaryTableOfDataEntity();
                threeMonthsSevere.setIndexId(riskFactorEntity.getInTheNextThreeMonthsSevereCode());
                threeMonthsSevere.setIndexValue(queryParams.getInTheNextThreeMonthsSevere());
                threeMonthsSevere.setDate(versionDate);
                temporaryTableOfDataEntities.add(threeMonthsSevere);
                temporaryTableOfDataService.saveBatch(temporaryTableOfDataEntities);
            }
        } catch (RRException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return new ResponseVO(e.getMessage());
        }
        return ResponseVO.ok();
    }

    @ApiOperation("导入风险因子值")
    @PostMapping(value = "/importRiskFactorValue")
    public ResponseVO importRiskFactorValue(@RequestParam("file") MultipartFile file, @RequestParam("excelType") Integer excelType, @RequestParam("versionTime") String date, HttpServletRequest request) {
        //判断文件是否为空
        String name = file.getOriginalFilename();
        Workbook wb = null;
        long size = file.getSize();
        if (null == file || null == name || SysConstant.ZERO == size) {
            return new ResponseVO(-1, "file is null");
        }
        try {
            InputStream inp = file.getInputStream();
            wb = WorkbookFactory.create(inp);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RRException("readExcel IO is error", e.getCause());
        }
        try {
            return riskFactorValueService.importRiskFactorValue(wb, excelType, date);
        } catch (RRException e) {
            e.printStackTrace();
            return new ResponseVO(e.getCode(), e.getMessage() + e.getCause().getMessage());
        }
    }


}